
/**
 * 2017/11/13
 */
import React, { Component, PropTypes } from 'react'
import { fetchPost } from './request'
import { Radio, Tooltip, Row, Checkbox, Popconfirm,  DatePicker, Table, Card, Button, Form, Upload, message, Modal, Select, Input, Icon, Col ,Tabs, InputNumber} from 'antd'

import {origin} from '../../../utils/config'
import {origin_promotion} from '../../../utils/config'

import moment from 'moment';
import Filter from './Filter.jsx';

const {MonthPicker, RangePicker} = DatePicker;
const FormItem = Form.Item
const Option = Select.Option
const CheckboxGroup = Checkbox.Group
const RadioGroup = Radio.Group
const TabPane = Tabs.TabPane
const formItemLayout = {
  labelCol: {span: 5},
  wrapperCol: {span: 12},
};

class List extends React.Component {
  constructor (props) {
    super(props)
    this.isModel = this.isModel.bind(this)
    this.editTemplate = this.editTemplate.bind(this)
    this.editRule = this.editRule.bind(this)
    this.isRuleModel = this.isRuleModel.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.getData = this.getData.bind(this)
    this.getInitRuleList = this.getInitRuleList.bind(this)
    this.changeIsLoading = this.changeIsLoading.bind(this)
    this.updateCoupontemplate = this.updateCoupontemplate.bind(this)
    this.changeTempleteStatus = this.changeTempleteStatus.bind(this)
    this.disabledDate = this.disabledDate.bind(this)
    this.getSearchData = this.getSearchData.bind(this)
    this.setRuleDataSelectValue = this.setRuleDataSelectValue.bind(this)
    this.handleRuleSubmit = this.handleRuleSubmit.bind(this)
    this.addRuleArr = this.addRuleArr.bind(this)
    this.deleteRuleArr = this.deleteRuleArr.bind(this)
    this.maxBorrowAmountValue = this.maxBorrowAmountValue.bind(this)
    this.minBorrowAmountValue = this.minBorrowAmountValue.bind(this)
    this.overDueDaysValue = this.overDueDaysValue.bind(this)
    this.IsOverdueCanUseFun = this.IsOverdueCanUseFun.bind(this)
    this.periodLimitValue = this.periodLimitValue.bind(this)
    this.isRollBackValue = this.isRollBackValue.bind(this)
    this.productCategoriesValue = this.productCategoriesValue.bind(this)
    this.isCanRecieveValue = this.isCanRecieveValue.bind(this)
    this.isSceneUse = this.isSceneUse.bind(this)
    this.ruleDetailTime = this.ruleDetailTime.bind(this)

    this.resetUserSearchParmas = this.resetUserSearchParmas.bind(this)
    this.changeMobile = this.changeMobile.bind(this)
    this.changeUserCode = this.changeUserCode.bind(this)
    this.handleUserSearch = this.handleUserSearch.bind(this)
    this.state = {
      data: [],
      startTime: null,
      endTime: null,
      fileList: [],
      batchNO: [],
      userList:[],
      checkBoxChoose: [],
      userChoose:[],
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
      visible: false,
      ruleVisible: false,
      isLoading: true,
      rowData: {},
      ruleList: [],
      productCodeList: [],
      ProductCategories: [],
      IsOverdueCanUse: true,
      batchgrant: false,
      specifygrant: false,
      defaultRuleList: [],
      rowRuleData:[{
        ruleCode: null,
        ruleDetail: {},
        ruleTemplateId:null,
        ruleTemplateName:"",
        ruleType: 3,
        required:null
      }],
      paramsCache: null,
      page: {
        currentPage: 1,
        pageSize: 10
      },
      userCode: null,
      mobile: null,
      checkAllProduct:false,
      productCodeValues:[],
      categoryType:0,
      appCode:5
    }
  }

  componentWillMount () {
    this.getData()
    this.getInitRuleList()
  }

  range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  disabledDate(current) {
    // Can not select days before today and today
    return current && current.valueOf() < Date.now();
  }
  getData () {
    // console.info("getData")
    // alert(this.state.rowRuleData.length);
    // alert(this.state.rowRuleData[0].ruleType);
    // this.state.rowRuleData[0].ruleDetail.minBorrowAmount = 50;
    // alert(this.state.rowRuleData[0].ruleDetail.minBorrowAmount);
    let postParams = {};
    if(this.state.paramsCache != null) {
      postParams = this.state.paramsCache;
      postParams.currentPage = this.state.page.currentPage;
      this.getSearchData(postParams);
    }
    else {
      postParams.pageSize = this.state.page.pageSize;
      postParams.currentPage = this.state.page.currentPage;
      let appCode = this.state.appCode
      fetchPost(`/coupontemplate/`+appCode+`/list`, postParams,origin_promotion).then(json => {
        if (json.data && json.code === 0) {
          let data = json.data.itemList
          this.state.page = json.data.page;
          this.setState({
            data: data,
            isLoading: false
          })
        }
      })
    }
  }
  getSearchData (params) {
    this.state.paramsCache = params;
    fetchPost(`/coupontemplate/queryByParams`,params,origin_promotion).then(json => {
      if (json.data && json.code === 0) {
        let data = json.data.itemList
        this.state.page = json.data.page;
        this.setState({
          data: data,
          isLoading: false
        })
      }
    })
  }

  getInitRuleList() {
    // console.info("getInitRuleList")
    let appCode = this.state.appCode
    fetchPost(`/coupontemplate/`+appCode+`/3/rulelist`,null , origin_promotion).then(json => {
      if (json.data && json.code === 0) {
        let code = [];
        json.data.ProductCategories.map(function (it) {
          let productcodes = it.productCodes;
          productcodes.map(function (k) {
            code.push({code:k.code,categoryCode:it.code,categoryType:k.categoryType})
          })
        })

        let content = [];
        json.data.ruleList.map(x => {
          let required = x.required;
          if (required == '1') {
            content.push({
              ruleType: x.ruleType,
              ruleTemplateName: x.ruleTemplateName,
              ruleDetail: JSON.parse(x.ruleDetail),
              ruleTemplateId: x.ruleTemplateId,
              ruleCode: x.ruleCode,
              required: x.required
            });
          }
        })
        content.map(x => {
          if(x.ruleCode === "IsOverdueCanUse") {
            x.ruleDetail={};
            x.ruleDetail.isOverdueCanUse = true;
          } else if(x.ruleCode === "IsRollBack") {
            x.ruleDetail={};
            x.ruleDetail.isRollBack = true;
          } else if(x.ruleCode === "IsCanRecieve") {
            x.ruleDetail={};
            x.ruleDetail.isCanRecieve = true;
          } else if(x.ruleCode === "SceneUse") {
            x.ruleDetail={};
            x.ruleDetail.sceneType = 1;
          }
        })
        this.setState({
          ruleList: json.data.ruleList.map(x => {
            return { label: x.ruleTemplateName, value: x.ruleTemplateId,ruleDetail:JSON.parse(x.ruleDetail), ruleCode: x.ruleCode,required:x.required }
          }),
          defaultRuleList: content,
          ProductCategories: json.data.ProductCategories.map(x => {
            return { label: x.name, value: x.code,categoryType:x.categoryType }
          }),

          productCodeList: code.map(x => {
            return { label: x.code, value: x.code , ruleCode: x.code,categoryCode:x.categoryCode,categoryType:x.categoryType}
          }),
          defaultProductCodeList: code.map(x => {
            return { label: x.code, value: x.code , ruleCode: x.code,categoryCode:x.categoryCode,categoryType:x.categoryType}
          }),
        })
      }
    })

  }

  changeIsLoading () {
    let a = !this.state.isLoading
    this.state.paramsCache = null;
    this.setState({
      isLoading: a
    })
  }
  addRuleArr() {
    let aa = this.state.rowRuleData;
    if (aa.length < this.state.ruleList.length) {
      aa.push({
        ruleCode: null,
        ruleDetail: {},
        ruleTemplateId:null,
        ruleTemplateName:"",
        ruleType: 3,
        required:null
      })
      this.setState({
        rowRuleData: aa,
      })
    }
  }
  deleteRuleArr (e) {
    const {resetFields} = this.props.form
    if (this.state.rowRuleData.length === 1) {
      message.error('Keep at least one rule')
      return
    }
    let aa = this.state.rowRuleData
    let tip = Number(e.target.id)
    aa.splice(tip, 1)
    resetFields()
    this.setState({
      rowRuleData: aa
    })
  }
  handleSubmit () {
    this.changeIsLoading()
    let self = this
    let appCode = this.state.appCode
    this.props.form.validateFields((err, values) => {
      if(!err) {
        let time = values.time
        let params = {}
        if(values.validtimeType !== '1') {
          values.startTime = time[0].format('YYYY-MM-DD HH:mm:ss'),
            values.endTime = time[1].format('YYYY-MM-DD HH:mm:ss')
          delete values.time
        }
        this.updateCoupontemplate(values, this.state.rowData.couponId)
      }
    })
  }
  handleRuleSubmit () {
    const { validateFields } = this.props.form
    validateFields((err, values) => {
      if(!err) {
        this.changeIsLoading()
        // this.state.rowRuleData.map(function (it) {
        //   let str = JSON.stringify(it); //转换成string
        // })
        let couponRule;
        couponRule = "[";
        let flag = 0;
        console.info(this.state.rowRuleData)
        this.state.rowRuleData.map(function (it) {
          let str = JSON.stringify(it); //转换成string
          if(flag != 0) {
            couponRule += ",";
          }
          else flag = 1;
          couponRule += str;
        })
        couponRule += "]";
        let params = {}
        params = {
          couponRules: couponRule
        };
        console.info(params.couponRules)
        fetchPost(`/coupontemplate/${this.state.rowData.couponId}/${this.state.categoryType}/updaterule`, params,origin_promotion).then(json => {
          if (json.data === null && json.code === 0) {
            message.success('Rule update succeeded')
            this.handleReset()
          } else {
            message.error(json.msg)
          }
        })
      }
    })
  }

  handleSubmitTo (e) {
    e.preventDefault()
    let self = this
    let appCode = this.state.appCode
    this.props.form.validateFields((error, values) => {
      let params = {}
      let couponsInfos = [];
      let valueArray = Object.values(values);
      let keyArray = Object.keys(values);
      let size = valueArray.length;

      this.state.checkBoxChoose.map(function (t) {
        let id = "ID" + t.couponId;
        for (let i = 0; i < size; i ++) {
          if (keyArray[i] == id) {
            let couponInfo = {};
            couponInfo.couponNum = valueArray[i];
            couponInfo.couponId = t.couponId;
            couponsInfos.push(couponInfo);
          }
        }
      })
      params = {
        batchNo : values.batchNo,
        couponsInfos : couponsInfos
      };

      fetchPost(`/grantcoupon/${appCode}/batchgrant`, params, origin_promotion).then(json => {
        if (json.code === 0) {
          message.success('Batch delivery success');
          this.handleReset()
        } else {
          message.error(json.msg);
        }
      });
    })
  }
  handleSubmitSpecify(e) {
    e.preventDefault()

    let appCode = this.state.appCode
    this.props.form.validateFields((error, values) => {
      let params = {}
      let couponsInfos = [];
      let valueArray = Object.values(values);
      let keyArray = Object.keys(values);
      console.info(valueArray)
      console.info(keyArray)
      let size = valueArray.length;
      let userCodes = [];
      this.state.userChoose.map(function (t) {
        userCodes.push(t.userCode);
      })

      this.state.checkBoxChoose.map(function (t) {
        let id = "ID" + t.couponId;
        for (let i = 0; i < size; i ++) {
          if (keyArray[i] == id) {
            let couponInfo = {};
            couponInfo.couponNum = valueArray[i];
            couponInfo.couponId = t.couponId;
            couponsInfos.push(couponInfo);
          }
        }
      })
      params = {
        userCodes: userCodes,
        couponsInfos : couponsInfos
      }
       fetchPost(`/grantcoupon/${appCode}/specifyGrantCoupons`, params, origin_promotion).then(json => {
         if (json.code === 0) {
           message.success('Designated successful delivery');
           this.handleReset()
         } else {
           message.error(json.msg);
         }
       });
    })
  }
  updateCoupontemplate(params, couponId) {
    fetchPost(`/coupontemplate/${couponId}/update`, params, origin_promotion).then(json => {
      if (json.code === 0) {
        message.success('Coupon editing success');
        this.handleReset()
      } else {
        message.error(json.msg);
      }
    });
  }
  setRuleDataSelectValue(value, index) {
    let aa = this.state.rowRuleData;
    let flag1 = 0;
    aa[index].ruleDetail={};
    aa.map(item => {
      if(item.ruleTemplateId === Number(value))  {
        message.error('Do not add repeating rules');
        this.props.value = null;
        flag1 = 1;
      }
    })
    if(flag1 === 0) {
      aa[index].ruleTemplateId = Number(value)
      this.state.ruleList.map(x => {
        if(x.value === aa[index].ruleTemplateId) {
          aa[index].ruleTemplateName = x.label
          aa[index].ruleCode = x.ruleCode
          if(aa[index].ruleCode === "IsOverdueCanUse") {
            aa[index].ruleDetail={};
            aa[index].ruleDetail.isOverdueCanUse = true;
          } else if(aa[index].ruleCode === "IsRollBack") {
            aa[index].ruleDetail={};
            aa[index].ruleDetail.isRollBack = true;
          } else if(aa[index].ruleCode === "IsCanRecieve") {
            aa[index].ruleDetail={};
            aa[index].ruleDetail.isCanRecieve = true;
          } else if(aa[index].ruleCode === "SceneUse") {
            aa[index].ruleDetail={};
            aa[index].ruleDetail.sceneType = 1;
          }
        }
      })
      this.setState({
        rowRuleData: aa
      })
    }
  }

  specifyModel() {
    return(
      <div>
      <Row align="middle">
        <Col span={9}>
          <FormItem {...formItemLayout} label={'User name'}>
            <Input placeholder="Please enter the user name" value={this.state.userCode} onChange={(e) => this.changeUserCode(e)} />
          </FormItem>
        </Col>
        <Col span={9}>
          <FormItem {...formItemLayout} label={'Mobile'}>
            <Input placeholder="Please enter the mobile" value={this.state.mobile} onChange={(e) => this.changeMobile(e)} />
          </FormItem>
        </Col>
        <Col span={6}>
          <Button type="primary" onClick={this.handleUserSearch}>Search</Button>
          <Button  style={{marginLeft :6}} onClick={this.resetUserSearchParmas}>Reset</Button>
        </Col>
      </Row>
      </div>
    )
  }
  batchModel() {
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 12},
    }
    if(this.state.batchgrant) {
      const { getFieldDecorator } = this.props.form
      let content = [];
      this.state.checkBoxChoose.map(function (t) {
        content.push(
          <FormItem
            {...formItemLayout}
            label={t.couponName}
          >
            {getFieldDecorator(`ID${t.couponId}`, {
              initialValue: 1,
              rules: [
                {required: false},
                {
                  pattern: /^[0-9]*$/,
                  message: "Please enter the valid format"
                }
              ]
            })(
              <InputNumber style={{ width: '100%' }} min={1} defaultValue={1}
              />
            )}
          </FormItem>
        )
      })
      return <Modal
        visible={this.state.batchgrant}
        onCancel={() => {
          this.handleReset()
        }}
        title='Batch send'
        footer={null}
      >
        <div>
          <Form style={{width: '100%', margin: 'auto'}} horizontal onSubmit={(e) => this.handleSubmitTo(e)}>
            <FormItem
              {...formItemLayout}
              label="Batch No"
            >
              {getFieldDecorator('batchNo', {
                rules: [
                  {required: true}
                ]
              })(
                <Select placeholder="Batch No">
                  {
                    this.state.batchNO.map(function (t) {
                      return(
                        <Option key={t.batchNo}>{t.batchNo}</Option>
                      )
                    })
                  }
                </Select>
              )}
            </FormItem>
            {content}
            <FormItem wrapperCol={{span: 12, offset: 6}}>
              <Button type="primary" htmlType="submit">Send</Button>
              &nbsp;
              <Button type="ghost" onClick={(e) => this.handleReset(e)}><Icon type="reload"/></Button>
            </FormItem>
          </Form>
        </div>
      </Modal>
    }
  }
  specifyGrantModel() {
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 12},
    }
    if(this.state.specifygrant) {
      const { getFieldDecorator } = this.props.form
      let content = [];
      this.state.checkBoxChoose.map(function (t) {
        content.push(
          <FormItem
            {...formItemLayout}
            label={t.couponName}
          >

            {getFieldDecorator(`ID${t.couponId}`, {
              initialValue: 1,
              rules: [
                {required: false},
                {
                  pattern: /^[0-9]*$/,
                  message: "Please enter the valid format"
                }
              ]
            })(
              <div>
              <InputNumber style={{ width: '80%' }} min={1} defaultValue={1}
              />

              </div>
            )}
          </FormItem>
        )
      })
      return <Modal
        visible={this.state.specifygrant}
        onCancel={() => {
          this.handleReset()
        }}
        title='Designated bond'
        footer={null}
      >
        <div>
          <Form style={{width: '100%', margin: 'auto'}} horizontal onSubmit={(e) => this.handleSubmitSpecify(e)}>
            {content}
            <FormItem wrapperCol={{span: 12, offset: 6}}>
              <Button type="primary" htmlType="submit">Send</Button>
              &nbsp;
              <Button type="ghost" onClick={(e) => this.handleReset(e)}><Icon type="reload"/></Button>
            </FormItem>
          </Form>
        </div>
      </Modal>
    }
  }
  isModel() {
    const {getFieldDecorator} = this.props.form
    const rowData = this.state.rowData
    // console.info(this.state.rowData.couponType)
    if(this.state.visible) {
      return <Modal
        visible={this.state.visible}
        onCancel={() => {
          this.handleReset()
        }}
        title='Edit coupon template'
        footer={null}
      >
        <div>
          <Form style={{width: '100%', margin: 'auto'}} horizontal >
            <FormItem
              {...formItemLayout}
              label="Lottery name"
            >
              {getFieldDecorator('couponName', {
                initialValue: rowData ? rowData.couponName : null,
                rules: [
                  {
                    required: true,
                    message: 'Please enter lottery name'
                  }
                ]
              })(
                <Input placeholder="Please enter lottery name"/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Valid time type"
            >
              {getFieldDecorator('validtimeType', {
                initialValue: rowData && rowData.validtimeType ? rowData.validtimeType.toString() : null,
              })(
                <Select onChange={(e) => {
                  this.setState({
                    params: {
                      ...this.state.params,
                      validtimeType: e
                    },
                    rowData: {
                      ...this.state.rowData,
                      validtimeType: e,
                      validTimeString: null,
                    }
                  })
                }} placeholder="Please select valid time type">
                  <Option key="1">relatively</Option>
                  <Option key="2">absolute</Option>
                </Select>
              )}
            </FormItem>

            {
              this.state.rowData.validtimeType && this.state.rowData.validtimeType.toString() === '1' ? <FormItem
                {...formItemLayout}
                label="Valid days"
              >
                {getFieldDecorator('validTime', {
                  initialValue: this.state.rowData && this.state.rowData.validTimeString ? this.state.rowData.validTimeString : null,
                  rules: [
                    {
                      pattern: /^[0-9]*$/,
                      message: 'Please enter number'
                    },
                    {
                      required: true,
                      message:'Please enter valid days'
                    },
                  ]
                })(
                  <Input placeholder="Please enter valid days"/>
                )}
              </FormItem> : null
            }

            {
              this.state.rowData.validtimeType && this.state.rowData.validtimeType.toString() === '2' ? <FormItem
                {...formItemLayout}
                label="Duration"
              >
                {getFieldDecorator('time', {
                  initialValue: this.state.rowData.validTimeString ? [moment(rowData.startTime), moment(rowData.endTime)]: null,
                  rules: [
                    {
                      required: true,
                      message:'Please select duration'
                    }
                  ]
                })(
                  <RangePicker
                    style={{width:'100%'}}
                    allowEmpty
                    showTime
                    disabledDate={this.disabledDate}
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                )}
              </FormItem> : null
            }
            <FormItem
              {...formItemLayout}
              label="Coupon type"
            >
              {getFieldDecorator('couponType', {
                initialValue: rowData && rowData.couponType ? rowData.couponType.toString() : null,
                rules: [
                  {
                    required: true
                  }
                ]
              })(
                <Select onChange={(e) => {
                  this.setState({
                    rowData: {
                      ...this.state.rowData,
                      couponType: e
                    },
                    params: {
                      ...this.state.params,
                      couponType: e
                    }
                  })
                }} placeholder="Please select the coupon type">
                  <Option key="1">Deduction</Option>
                  <Option key="2">Discount</Option>
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Coupon amount"
            >
              {getFieldDecorator('couponAmount', {
                initialValue: rowData ? rowData.couponAmount : null,
                rules: [
                  {
                    pattern: /^([1-9]\d*|0)(\.\d{1,})?$/,
                    message: 'Please enter number'
                  },
                  {
                    required: true,
                    message:'Please enter the coupon amount'
                  }
                ]
              })(
                <div>
                <Input placeholder="Please enter the coupon amount" style={{width: '80%'}} defaultValue={rowData ? rowData.couponAmount : null}/>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {
                    rowData.couponType == 1 ?
                      <span style={{textAlign: 'right'}}>rupee</span> :
                      <span style={{textAlign: 'right'}}>fold</span>
                  }
                </div>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Description"
            >
              {getFieldDecorator('couponDesc', {
                initialValue: rowData ? rowData.couponDesc : null,
                rules: [
                  {
                    required: true,
                    message:'Please enter the description'
                  }
                ]
              })(
                <Input placeholder="Please enter the description"/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Total"
            >
              {getFieldDecorator('totalNum', {
                initialValue: rowData ? rowData.totalNum : null,
                rules: [
                  {
                    pattern: /^[0-9]*$/,
                    message: 'Please enter a positive integer'
                  },
                  {
                    required: true,
                    message:'Plaese enter the total'
                  }
                ]
              })(
                <InputNumber style={{width: '100%'}} min={0} ></InputNumber>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="App channel"
            >
              {getFieldDecorator('appCode', {
                initialValue: rowData && rowData.appCode ? rowData.appCode.toString() : null,
                rules: [
                  {
                    required: true,
                    message:'Please enter the app channel type'
                  }
                ]
              })(
                <Select onChange={(e) => {
                  this.setState({
                    params: {
                      ...this.state.params,
                      appCode: e
                    }
                  })
                }} placeholder="Please enter the app channel type">

                  <Option  key="5" disabled>JYD</Option>
                  <Option  key="2" disabled>SDZZ</Option>
                </Select>
              )}
            </FormItem>
            <FormItem wrapperCol={{span: 12, offset: 5}}>
              <Button type="primary" onClick={this.handleSubmit}>OK</Button>
              <Button style={{marginLeft:16}}type="ghost" onClick={(e) => this.handleReset(e)}>Cancel</Button>
            </FormItem>
          </Form>
        </div>
      </Modal> }
  }
  isRuleModel() {
    const {getFieldDecorator} = this.props.form
    const rowRuleData = this.state.rowRuleData
    if(this.state.ruleVisible) {
      return <Modal
        visible={this.state.ruleVisible}
        onCancel={() => {
          this.handleReset()
        }}
        title='Edit coupon rules'
        footer={null}
      >
        <div>
          <Form style={{width: '100%', margin: 'auto'}} horizontal >
             {rowRuleData && rowRuleData.map((x, index) => {

               if(this.state.rowData.couponRules.length==0&& x.required==0){
                  return;
                }
               return <div style={{position:'relative'}} key={index}>
                <FormItem {...formItemLayout} label={`Lottery rules${index + 1}`} style={{fontWeight: 'bold'}}>
                  {getFieldDecorator(`ruleTemplateId${index}`, {
                    initialValue: x.ruleTemplateId && x.ruleTemplateId.toString(),
                    rules: [
                      {
                        required: true,
                        message:'Please select the lottery rules'
                      }
                    ]})(
                    <Select
                      onChange={(e) => this.setRuleDataSelectValue(e, index)}
                      placeholder="Please Select"
                    >
                      {
                        this.state.ruleList.map((y, ruleIndex) => {
                            return <Option key={ruleIndex} value = {y.value && y.value.toString()}>{y.label}</Option>
                        })
                      }
                    </Select>

                  )}
                  <div style={{position: 'absolute', top: 1, right: '-75px'}}>
                    <Button onClick={() => this.addRuleArr()} type="primary" size={'small'} ><Icon type="plus" /></Button>
                    {
                      this.isRuleRequired(index,x)
                    }
                  </div>
                </FormItem>

                {
                  this.renderRuleDetail(x.ruleTemplateId, x.ruleDetail, x.ruleCode)
                }
              </div>
            })
            }
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <FormItem wrapperCol={{span: 12, offset: 5}}>
              <Button type="primary" onClick={this.handleRuleSubmit}>OK</Button>
              <Button style={{marginLeft:16}}type="ghost" onClick={(e) => this.handleReset(e)}>Cancel</Button>
            </FormItem>
          </Form>
        </div>
      </Modal>
    }
  }

  handleUserSearch() {
    let userCode = this.state.userCode;
    let mobile = this.state.mobile;
    if((userCode == null || userCode === "") && (mobile == null || mobile === "") ) {
      message.error("Please enter userCode or mobile");
      return;
    }
    let postParams = {};
    if (userCode != null && userCode != "") {
      postParams.userCode = userCode;
    }
    if (mobile != null && userCode != "") {
      postParams.mobile = mobile;
    }
    fetchPost(`/grantcoupon/queryusers`, postParams,origin_promotion).then(json => {
      if (json.code === 0) {
        message.success('Get user info successful');
        this.setState({
          userList: json.data.itemList
        })
      } else {
        message.error(json.msg);
      }
    })
    //
    // const { validateFields } = this.props.form
    // validateFields((err, values) => {
    //   if(!err){
    //     let aa = {}
    //     if(values.couponNameS) {
    //       aa.couponName = values.couponNameS;
    //     }
    //     if(values.couponTypeS) {
    //       aa.couponType = values.couponTypeS;
    //     }
    //     aa.pageSize = 10;
    //     aa.currentPage = 1;
    //     this.props.getUserSearchData(aa)
    //   }
    // })
  }
  resetUserSearchParmas () {
    this.setState({
      mobile: null,
      userCode: null
    })
  }

  minBorrowAmountValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if (x.ruleCode === "BorrowAmount") x.ruleDetail.minBorrowAmount = e.target.value
    })
    this.setState({
      rowRuleData: aa
    })
  }
  maxBorrowAmountValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "BorrowAmount") x.ruleDetail.maxBorrowAmount = e.target.value
    })
    this.setState({
      rowRuleData: aa
    })
  }
  overDueDaysValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "IsOverdueCanUse") x.ruleDetail.overDueDays = e.target.value
    })
    this.setState({
      rowRuleData: aa
    })
  }
  periodLimitValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "PeriodLimit") x.ruleDetail.periodLimit = e.target.value
    })
    this.setState({
      rowRuleData: aa
    })
  }
  IsOverdueCanUseFun (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "IsOverdueCanUse") {
        x.ruleDetail.isOverdueCanUse = e.target.value
        if(e.target.value === 'false') x.ruleDetail.overDueDays = null
      }
    })
    this.setState({
      rowRuleData: aa,
      IsOverdueCanUse: e.target.value === 'true' ? true : false
    })
  }
  isCanRecieveValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "IsCanRecieve") x.ruleDetail.isCanRecieve = e
    })
    this.setState({
      rowRuleData: aa,
    })
  }

  isSceneUse (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "SceneUse") x.ruleDetail.sceneType = e
    })
    this.setState({
      rowRuleData: aa,
    })
  }
  isRollBackValue (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "IsRollBack") x.ruleDetail.isRollBack = e
    })
    this.setState({
      rowRuleData: aa,
    })
  }
  productCategoriesValue(e) {
    let origin = this.state.defaultProductCodeList;
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "ProductCategory") x.ruleDetail.productCategories = e
    })
    this.setState({
      rowRuleData: aa,
    })

    let arr = [];
    for(let i in origin ){
      for(let j in e){
        if(origin[i].categoryCode == e[j]){
          arr.push(origin[i]);
        }
      }
    }
    if(e.length ==0){
      arr = origin;
    }
    this.setState({
      productCodeList:arr
    })

    let categories = this.state.ProductCategories
    let dq = false
    let fq = false
    for(let i in categories){
      for(let j in e){
        if(categories[i] != e[j]){
          continue
        }
        if(categories[i].categoryType == 1){
          dq = true
        }
        if(categories[i].categoryType == 2){
          fq = true
        }
      }

    }
    if(dq && !fq){
      this.state.categoryType = 1
    }
    if(!dq && fq){
      this.state.categoryType = 2
    }
  }
  selectAllProduct(e){
    let checkedAll = e.target.checked
    let productCodes  = this.state.productCodeList;
    let aa = this.state.rowRuleData
    let pCodes = [];
    let temp = [];
    if(checkedAll){
      let arr = this.state.productCodeList;
      for(let ii in arr){
        temp.push(arr[ii].value)
      }
    }
    aa.map(x => {
      if(x.ruleCode === "ProductCode") x.ruleDetail.productCodes = temp
    })
    this.setState({
      rowRuleData: aa,
    })
    this.setState({
      productCodeValues:temp
    })


    let products = this.state.productCodeList
    let dq = false
    let fq = false
    for(let i in products){
      for(let j in e){
        if(products[i] != e[j]){
          continue
        }
        if(products[i].categoryType == 1){
          dq = true
        }
        if(products[i].categoryType == 2){
          fq = true
        }
      }
    }
    if(dq && !fq){
      this.state.categoryType = 1
    }
    if(!dq && fq){
      this.state.categoryType = 2
    }
  }
  productCodesValue(e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "ProductCode") x.ruleDetail.productCodes = e
    })
    this.setState({
      rowRuleData: aa,
    })

    let isExists = false;
    let temp = this.state.productCodeValues
    temp = e
    /*temp.map(x=>{
      if(x==e[0]){
        isExists = true
      }
      if(x != e){
        return x;
      }
    })

    if(!isExists){
      temp.push(e[0])
    }*/
    this.setState({
      productCodeValues:temp
    })
    let products = this.state.productCodeList
    let dq = false
    let fq = false
    for(let i in products){
      for(let j in e){
        if(products[i] != e[j]){
          continue
        }
        if(products[i].categoryType == 1){
          dq = true
        }
        if(products[i].categoryType == 2){
          fq = true
        }
      }
    }
    if(dq && !fq){
      this.state.categoryType = 1
    }
    if(!dq && fq){
      this.state.categoryType = 2
    }
    //let currentProductCodes = []

    //this.state.productCodeValues.push(e)
  }
  ruleDetailTime (e) {
    let aa = this.state.rowRuleData
    aa.map(x => {
      if(x.ruleCode === "RecieveValidTime") {
        x.ruleDetail.startTime = e[0].format('YYYY-MM-DD HH:mm:ss')
        x.ruleDetail.endTime = e[1].format('YYYY-MM-DD HH:mm:ss')
      }
    })
    this.setState({
      rowRuleData: aa,
    })
  }
  isRuleRequired(index,x){
    if(x.required===0){
      return <Button id={`${index}`} onClick={(e) => this.deleteRuleArr(e)} size={'small'} style={{marginLeft: 6}}><Icon type="minus" /></Button>
    }
    return
  }
  renderRuleDetail(ruleTemplateId, renderData, ruleCode) {
    if(!ruleTemplateId) return false
    const {getFieldDecorator} = this.props.form

    switch (ruleCode) {
      case "BorrowAmount":
        return <div key={ruleTemplateId}>
          <FormItem
            {...formItemLayout}
            label="Minimum borrowing amount"
          >
            {getFieldDecorator('minBorrowAmount', {
              initialValue: renderData && renderData.minBorrowAmount ? renderData.minBorrowAmount: null,
              rules: [
                {
                  pattern: /^([1-9]\d*|0)(\.\d{1,})?$/,
                  message: 'Please enter number'
                }
              ]
            })(
              <Input placeholder='Please enter the minimum Loan Amount'
                     onBlur={(e) => this.minBorrowAmountValue(e)}
                />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={'Maximum Loan Amount'}>
            {getFieldDecorator('maxBorrowAmount', {
              initialValue: renderData && renderData.maxBorrowAmount ? renderData.maxBorrowAmount: null,
              rules: [
                {
                  pattern: /^([1-9]\d*|0)(\.\d{1,})?$/,
                  message: 'Please enter number'
                }
              ]
            })(
              <Input placeholder='Please enter the maximum Loan Amount'
                     onBlur={(e) => this.maxBorrowAmountValue(e)}
              />
            )}
          </FormItem>
        </div>
        break;
      case "IsOverdueCanUse":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Can it be used after the deadline?'}>
            <RadioGroup
              onChange={(e) => this.IsOverdueCanUseFun(e)}
              defaultValue={renderData && renderData.isOverdueCanUse === false ? 'false' : 'true'}
            >
              <Radio value={'true'}>Yes</Radio>
              <Radio value={'false'}>No</Radio>
            </RadioGroup>
          </FormItem>
          {
            renderData.isOverdueCanUse == true ?
            <FormItem {...formItemLayout} label={'Number of days used'}>
              {getFieldDecorator('overDueDays', {
                initialValue: renderData && renderData.overDueDays ? renderData.overDueDays: null,
                rules: [
                  {
                    pattern: /^[0-9]*$/,
                    message: 'Please enter number'
                  }
                ]
              })(
                <Input placeholder='Please enter the number of days used'
                       onBlur={(e) => this.overDueDaysValue(e)}
                />
              )}
            </FormItem> : null
          }
        </div>
        break;
      case "IsRollBack":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Is it refundable'}>
            <RadioGroup
              defaultValue={renderData && renderData.isRollBack === false ? 'false' : 'true'}
              onChange={(e) => this.isRollBackValue(e.target.value)}
            >
              <Radio value={'true'}>Yes</Radio>
              <Radio value={'false'}>No</Radio>
            </RadioGroup>
          </FormItem>
        </div>
        break;
      case "PeriodLimit":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Period limit'}>
            <InputNumber placeholder='Please enter the period limit' min={1}
                   defaultValue={renderData && renderData.periodLimit ? renderData.periodLimit : 1}
                   onBlur={(e) => this.periodLimitValue(e)}
            />
          </FormItem>
        </div>
        break;
      case "ProductCategory":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Product category restrictions'}>
            <CheckboxGroup options={this.state.ProductCategories}
                           onChange={(e) => this.productCategoriesValue(e)}
                           defaultValue={renderData && renderData.productCategories ? renderData.productCategories : []}
            />
          </FormItem>
        </div>
        break;
      case "SceneUse":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Voucher use scene limit'}>
            <RadioGroup
              defaultValue={renderData && renderData.sceneType?renderData.sceneType:1}
              onChange={(e) => this.isSceneUse(e.target.value)}
            >
              <Radio value={1}>借款</Radio>
              <Radio value={2}>还款</Radio>
            </RadioGroup>
          </FormItem>
        </div>
        break;

      case "ProductCode":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Product code limit'}>
            <label>
              <Checkbox defaultChecked={false} onChange={(e)=> this.selectAllProduct(e)}
                       />
              全选
            </label>
            <CheckboxGroup  options={this.state.productCodeList}
                            value={this.state.productCodeValues.length != 0 ?this.state.productCodeValues:renderData.productCodes}
                           onChange={(e) => this.productCodesValue(e)}
                           defaultValue={renderData && renderData.productCodes ? renderData.productCodes : []}
            >
            </CheckboxGroup>
          </FormItem>
        </div>
        break;
      case "IsCanRecieve":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Can it be used'}>
            <RadioGroup
              defaultValue={renderData && renderData.isCanRecieve === false ? 'false' : 'true'}
              onChange={(e) => this.isCanRecieveValue(e.target.value)}
            >
              <Radio value={'true'}>Yes</Radio>
              <Radio value={'false'}>No</Radio>
            </RadioGroup>
          </FormItem>
        </div>
        break;
      case "RecieveValidTime":
        return <div key={ruleTemplateId}>
          <FormItem {...formItemLayout} label={'Coupon time limit'}>
            <RangePicker
              style={{width:'100%'}}
              allowEmpty
              showTime
              disabledDate={this.disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
              defaultValue={renderData && renderData.startTime ? [moment(renderData.startTime), moment(renderData.endTime)] : []}
              onOk={(e) => this.ruleDetailTime(e)}
            />
          </FormItem>
        </div>
        break;
      default: break;
    }
  }
  editRule (data) {
    // console.info(this.state.ruleList.size())
    // console.info(this.state.ruleList.length)
    if (this.state.ruleList.length <= 0) {
      message.error("No rules were obtained，please try again later");
      return;
    }
    this.setState({
      ruleVisible: true,
      rowData: data,
      rowRuleData: data.couponRules.length > 0 ? data.couponRules : this.state.defaultRuleList,
    }, () => {
      this.isRuleModel()
    })
  }
  handleReset () {
    this.props.form.resetFields()
    this.setState({
      data: [],
      startTime: null,
      endTime: null,
      fileList: [],
      batchNO: [],
      checkBoxChoose: [],
      batchgrant: false,
      specifygrant: false,
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
      visible: false,
      ruleVisible: false,
      isLoading: true,
      rowData: {},
      ruleList: [],
      ProductCategories: [],
      rowRuleData:[{
        ruleCode: null,
        ruleDetail: {},
        ruleTemplated:null,
        ruleTemplateName:"",
        ruleType: 3,
      }],
      page: {
        currentPage: 1,
        pageSize: 10
      }
    }, () => {
      this.getInitRuleList()
      this.getData()
    })
  }
  deleteTemplete(couponId) {
    this.changeIsLoading()
    fetchPost(`/coupontemplate/${couponId}/delete`, null, origin_promotion).then(json => {
      if (json.code === 0) {
        message.success('Lottery ticket deleted successfully');
        this.handleReset()
      } else {
        message.error(json.msg);
      }
    });
  }
  changeTempleteStatus (data) {
    this.changeIsLoading()
    if(data.status === 1) {
      fetchPost(`/coupontemplate/${data.couponId}/offline`, null, origin_promotion).then(json => {
        if (json.code === 0) {
          message.success('Coupon is offline');
          this.handleReset()
        } else {
          message.error(json.msg);
        }
      })
    } else {
      fetchPost(`/coupontemplate/${data.couponId}/online`, null, origin_promotion).then(json => {
        if (json.code === 0) {
          message.success('Coupon online successfully');
          this.handleReset()
        } else {
          message.error(json.msg);
        }
      })
    }
  }
  editTemplate (data) {
    this.setState({
      visible: true,
      rowData: data
    }, (rowData) => {
      // console.info(this.state.rowData.couponType)
      this.isModel()
    })
  }
  getBatchNolist() {
    fetchPost(`/grantcoupon/batchnolist`, null, origin_promotion).then(json => {
      if (json.data && json.code === 0) {
        // let data = json.data.itemList
        this.state.batchNO = json.data.batchList
        this.setState({
          batchNO: json.data.batchList
        })
      }
    })
  }

  specifygrantfuc(e) {
    if(this.state.checkBoxChoose.length === 0) {
      message.error("No choice coupon template");
      return;
    }
    if(this.state.userChoose.length === 0) {
      message.error("User not selected");
      return;
    }
    this.setState({
      specifygrant: true
    })
  }
  batchgrantfuc(e) {
    if(this.state.checkBoxChoose.length === 0) {
      message.error("No choice coupon template");
      return;
    }
    this.setState({
      batchgrant: true
    })
    this.getBatchNolist();
  }
  checkboxchange(e) {
    for (let i = 0; i < this.state.checkBoxChoose.length; i ++) {
      if(this.state.checkBoxChoose[i].couponId == e.couponId) {
        this.state.checkBoxChoose.splice(i, 1);
        return;
      }
    }
    // message.info("ok")
    let entity = {};
    entity.couponId = e.couponId;
    entity.couponName = e.couponName;
    this.state.checkBoxChoose.push(entity);
  }
  usercheckboxchange(e) {
    for (let i = 0; i < this.state.userChoose.length; i ++) {
      if(this.state.userChoose[i].userCode == e.userCode) {
        this.state.userChoose.splice(i, 1);
        return;
      }
    }
    // message.info("ok")
    let entity = {};
    entity.userCode = e.userCode;
    this.state.userChoose.push(entity);
  }
  nextPage (currentPage) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage,
      }
    }, () => {
      this.getData()
    })
  }

  changeMobile(e) {
    this.setState({
      mobile: e.target.value,
    })
  }
  changeUserCode(e) {
    this.setState({
      userCode: e.target.value,
    })
  }
  render () {
    let self = this
    const userColumns = [
      {
        title: 'Select',
        dataIndex: '',
        key: '',
        render: (text, record) => {
          return (
            <Checkbox value={record.userCode} onChange = {() => this.usercheckboxchange(record)} />
          )
        }
      }, {
        title: 'Name',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: 'UserCode',
        dataIndex: 'userCode',
        key: 'userCode'
      }, {
        title: 'Mobile',
        dataIndex: 'mobile',
        key: 'mobile'
      }
    ]
    const columns = [
      {
        title: 'Select',
        dataIndex: '',
        key: '',
        render: (text, record) => {
          if(record.status == 1) {
            return (
              <Checkbox value={record.couponId} onChange = {() => this.checkboxchange(record)}></Checkbox>
            )
          }
        }
      }, {
        title: 'Lottery name',
        dataIndex: 'couponName',
        key: 'couponName'
      }, {
        title: 'Lottery type',
        dataIndex: 'couponTypeString',
        key: 'couponTypeString'
      }, {
        title: 'Lottery denomination',
        dataIndex: 'couponAmount',
        key: 'couponAmount'
      }, {
        title: 'app',
        dataIndex: 'appCodeString',
        key: 'appCodeString'
      }, {
        title: 'Total number of coupons',
        dataIndex: 'totalNum',
        key: 'totalNum'
      }, {
        title: 'The remaining amount',
        dataIndex: 'remainNum',
        key: 'remainNum'
      }, {
        title: 'Effective time',
        dataIndex: 'validTimeString',
        key: 'validTimeString'
      }, {
        title: 'Status',
        dataIndex: 'statusString',
        key: 'statusString'
      }, {
        title: 'Operation',
        key: 'operation',
        render: (text, record) => {
          if(record.status === 2) {
            return<div style={{display:'flex',flexDirection: 'row',justifyContent: 'center'}}>
              <Popconfirm  title={`Whether to delete the lottery`} onConfirm={() => this.deleteTemplete(record.couponId)}>
                <a style={{ margin : 5 }}>Delete</a>
              </Popconfirm>
              <a  style={{ margin : 5,  color: '#87CEEB'  }}  onClick={() => this.editTemplate(record)}>Edit</a>
              <a  onClick={() => this.editRule(record)} style={{ margin : 5, color: '#87CEEB' }}>Edit the rule</a>
            </div>
          }
          return <div style={{display:'flex',flexDirection: 'row',justifyContent: 'center'}}>
            <Popconfirm  title={`Whether to delete the lottery`} onConfirm={() => this.deleteTemplete(record.couponId)}>
              <a style={{ margin : 5 }}>Delete</a>
            </Popconfirm>
            <a  onClick={() => this.editTemplate(record)} style={{ margin : 5,  color: '#87CEEB'  }}>Edit</a>
            <Popconfirm  title={`Whether ${record.status === 1 ? 'offline': 'online'} the lottery`}  onConfirm={() => this.changeTempleteStatus(record)}>
              {
                record.status === 1 ? <a style={{ margin : 5,  }}>offline</a> :
                  <a style={{ margin : 5,  color: '#00CD66'  }}>online</a>
              }
            </Popconfirm>
            <a onClick={() => this.editRule(record)}  style={{ margin : 5, color: '#87CEEB' }}>Edit rule</a>
          </div>
        },
      }]
    const { getFieldDecorator } = this.props.form
    const pagination = {
      total: self.state.page.totalCount,
      pageSize: self.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.nextPage(current)
      }
    }
    return (
      <div>
        <Card>
          <Filter changeIsLoading={this.changeIsLoading} getSearchData={this.getSearchData} getData={this.getData}/>

          {this.isModel()}
          {this.isRuleModel()}
          {this.batchModel()}
          {this.specifyGrantModel()}
          <Card>
            <Tabs defaultActiveKey="1">
              <TabPane tab="Send designated lottery" key="1">

                <Button type="primary" style={{marginLeft: 10}} ghost onClick={(e) => {
                  this.specifygrantfuc(e);
                }}>
                  Send designated lottery
                </Button>
                <br/>
                <br/>
                <Card>
                  {this.specifyModel()}
                <Table key="userList" style={{marginTop:36}} columns={userColumns} dataSource={self.state.userList}
                       bordered
                >
                </Table>
                </Card>
              </TabPane>
              <TabPane tab="Batch send lottery" key="2">
                <Button type="primary" style={{marginLeft: 10}} ghost onClick={(e) => {
                  this.batchgrantfuc(e);
                }}>
                  Batch send lottery
                </Button>
              </TabPane>
            </Tabs>
          </Card>
          <Table key="couponTemplateList" loading={this.state.isLoading} style={{marginTop:36}} pagination={pagination} columns={columns} dataSource={self.state.data}
                 bordered
          >
          </Table>
          <br/>
        </Card>
      </div>
    )
  }
}

export default Form.create()(List)


